using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using ExamPaperEditingSystem.Models;

namespace ExamPaperEditingSystem.Services
{
    /// <summary>
    /// 配置服务实现
    /// </summary>
    public class ConfigurationService : IConfigurationService
    {
        private readonly string _aiConfigFilePath;
        private readonly string _uiConfigFilePath;
        private readonly HttpClient _httpClient;
        private AIConfiguration? _cachedAIConfiguration;
        private UIConfiguration? _cachedUIConfiguration;

        public ConfigurationService()
        {
            // 配置文件保存在应用程序目录下
            var appDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ExamPaperEditingSystem");
            Directory.CreateDirectory(appDataPath);
            _aiConfigFilePath = Path.Combine(appDataPath, "ai_config.json");
            _uiConfigFilePath = Path.Combine(appDataPath, "ui_config.json");

            _httpClient = new HttpClient();
            _httpClient.Timeout = TimeSpan.FromSeconds(10); // 测试连接时使用较短超时
        }

        public async Task<AIConfiguration> GetAIConfigurationAsync()
        {
            if (_cachedAIConfiguration != null)
            {
                return _cachedAIConfiguration;
            }

            try
            {
                if (File.Exists(_aiConfigFilePath))
                {
                    var json = await File.ReadAllTextAsync(_aiConfigFilePath, Encoding.UTF8);
                    var config = JsonSerializer.Deserialize<AIConfiguration>(json, new JsonSerializerOptions
                    {
                        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                        WriteIndented = true
                    });

                    _cachedAIConfiguration = config ?? AIConfiguration.CreateDefault();
                }
                else
                {
                    _cachedAIConfiguration = AIConfiguration.CreateDefault();
                    await SaveAIConfigurationAsync(_cachedAIConfiguration);
                }
            }
            catch (Exception ex)
            {
                // 如果加载配置失败，使用默认配置
                System.Diagnostics.Debug.WriteLine($"加载AI配置失败: {ex.Message}");
                _cachedAIConfiguration = AIConfiguration.CreateDefault();
            }

            return _cachedAIConfiguration;
        }

        public async Task SaveAIConfigurationAsync(AIConfiguration configuration)
        {
            try
            {
                var json = JsonSerializer.Serialize(configuration, new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                    WriteIndented = true,
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                });

                await File.WriteAllTextAsync(_aiConfigFilePath, json, Encoding.UTF8);
                _cachedAIConfiguration = configuration.Clone();
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"保存AI配置失败: {ex.Message}", ex);
            }
        }

        public async Task ResetToDefaultAsync()
        {
            var defaultConfig = AIConfiguration.CreateDefault();
            await SaveAIConfigurationAsync(defaultConfig);
        }

        public async Task<bool> TestApiConnectionAsync(string apiUrl, bool isEmbeddingApi = false)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(apiUrl))
                {
                    return false;
                }

                object testRequest;
                if (isEmbeddingApi)
                {
                    // 测试嵌入向量API
                    testRequest = new
                    {
                        input = "test",
                        model = "text-embedding-bge-m3"
                    };
                }
                else
                {
                    // 测试聊天API
                    testRequest = new
                    {
                        model = "test-model",
                        messages = new[]
                        {
                            new { role = "user", content = "test" }
                        },
                        max_tokens = 10,
                        temperature = 0.1
                    };
                }

                var json = JsonSerializer.Serialize(testRequest, new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                });

                var content = new StringContent(json, Encoding.UTF8, "application/json");
                
                using var response = await _httpClient.PostAsync(apiUrl, content);
                
                // 即使返回错误状态码，只要能连接到服务器就认为连接成功
                // 因为我们只是测试连接性，不是测试API的完整功能
                return response != null;
            }
            catch (HttpRequestException)
            {
                // 网络连接错误
                return false;
            }
            catch (TaskCanceledException)
            {
                // 超时
                return false;
            }
            catch (Exception ex)
            {
                // 其他错误，记录日志但不抛出异常
                System.Diagnostics.Debug.WriteLine($"测试API连接时发生错误: {ex.Message}");
                return false;
            }
        }

        public async Task<UIConfiguration> GetUIConfigurationAsync()
        {
            if (_cachedUIConfiguration != null)
            {
                return _cachedUIConfiguration;
            }

            try
            {
                if (File.Exists(_uiConfigFilePath))
                {
                    var json = await File.ReadAllTextAsync(_uiConfigFilePath, Encoding.UTF8);
                    var config = JsonSerializer.Deserialize<UIConfiguration>(json, new JsonSerializerOptions
                    {
                        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                        WriteIndented = true
                    });

                    _cachedUIConfiguration = config ?? UIConfiguration.CreateDefault();
                }
                else
                {
                    _cachedUIConfiguration = UIConfiguration.CreateDefault();
                    await SaveUIConfigurationAsync(_cachedUIConfiguration);
                }
            }
            catch (Exception ex)
            {
                // 如果加载配置失败，使用默认配置
                System.Diagnostics.Debug.WriteLine($"加载UI配置失败: {ex.Message}");
                _cachedUIConfiguration = UIConfiguration.CreateDefault();
            }

            return _cachedUIConfiguration;
        }

        public async Task SaveUIConfigurationAsync(UIConfiguration configuration)
        {
            try
            {
                var json = JsonSerializer.Serialize(configuration, new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                    WriteIndented = true,
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                });

                await File.WriteAllTextAsync(_uiConfigFilePath, json, Encoding.UTF8);
                _cachedUIConfiguration = configuration.Clone();
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"保存UI配置失败: {ex.Message}", ex);
            }
        }



        public void Dispose()
        {
            _httpClient?.Dispose();
        }
    }
}
